package io.yuncheng.common.utils;

import com.alibaba.fastjson.JSON;
import io.yuncheng.modules.sys.entity.xml.XmlTaskEntity;
import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
/**
 * xml字符转化对象
 *
 * @Author shouxu
 * @Date 2022/5/12 15:44
 */
@Slf4j
public class XmlUtil {
    public static void main(String[] args) {
                String str = "\t<task>\n" +
                        "\t\t<user>\n" +
                        "\t\t\t<oper>mod</oper>\n" +
                        "\t\t\t<!--操作类型（修改用户）-->\n" +
                        "\t\t\t<id>14000001@gd.zg</id>\n" +
                        "\t\t\t<!--用户信任号-->\n" +
                        "\t\t\t<name>张三</name>\n" +
                        "\t\t\t<!--用户姓名-->\n" +
                        "\t\t\t<usertype/>\n" +
                        "\t\t\t<!--用户类型UT01：个人证书用户，UT02：法人证书用户-->\n" +
                        "\t\t\t<dname>会议处</dname>\n" +
                        "\t\t\t<!--用户所属机构名称-->\n" +
                        "\t\t\t<did>34000001@gd.zg</did>\n" +
                        "\t\t\t<!--用户所属机构标识-->\n" +
                        "\t\t\t<dorder/>\n" +
                        "\t\t\t<!--用户排序号-->\n" +
                        "\t\t\t<dcode/>\n" +
                        "\t\t\t<!--用户所属机构编码-->\n" +
                        "\t\t\t<sexual>1</sexual>\n" +
                        "\t\t\t<!--用户性别1:男，0：女-->\n" +
                        "\t\t\t<duty/>\n" +
                        "\t\t\t<!--用户职务-->\n" +
                        "\t\t\t<post/>\n" +
                        "\t\t\t<!--用户岗位-->\n" +
                        "\t\t\t<account/>\n" +
                        "\t\t\t<!--用户账号-->\n" +
                        "\t\t\t<password/>\n" +
                        "\t\t\t<!--用户密码-->\n" +
                        "\t\t\t<mail/>\n" +
                        "\t\t\t<!--安全邮箱-->\n" +
                        "\t\t</user>\n" +
                        "\n" +
                        "\t</task>\n";
        XmlTaskEntity xmlTaskEntity = xmlParseEntity(str);
        System.out.println(JSON.toJSONString(xmlTaskEntity));

    }

    public static XmlTaskEntity xmlParseEntity(String xmlStr){
        log.info("xmlParseEntity 入参字符:{}",xmlStr);
        XmlTaskEntity xmlTaskEntity = new XmlTaskEntity();
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(XmlTaskEntity.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Object unmarshal = unmarshaller.unmarshal(new StringReader(xmlStr));
            xmlTaskEntity = (XmlTaskEntity) unmarshal;
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        log.info("xmlParseEntity 返回对象:{}", JSON.toJSONString(xmlTaskEntity) );
        return xmlTaskEntity;
    }
}
